<?php

namespace app\admin\framework\controller;

use app\admin\framework\api\Permission;
use app\common\model\File;
use app\common\utils\UploadFile;


#[Permission('文件管理', 'System')]
class FileController
{
    
    public $noNeedAuth = ['upload'];
    
    #[Permission('参数')]
    public function option()
    {
        return apiSuccess(data: [
            'fileType' => File::FILE_TYPE,
            'storages' => File::STORAGES
        ]);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $data = request()->get();
        $result = File::where(function ($query) use ($data) {
            if (!empty($data['keyword'])) {
                $query->where('title', 'like', '%' . $data['keyword'] . '%');
            }
            if (!empty($data['fileType'])) {
                $query->where('file_type', $data['fileType']);
            }
            if (!empty($data['storage'])) {
                $query->where('storage', $data['storage']);
            }
            if (!empty($data['timeBetween'])) {
                $query->where('create_time', 'between', $data['timeBetween']);
            }
        })->append(['file_type_text'])->order('id desc')->paginate();
        return apiSuccess(data: ['list' => $result->items(), 'total' => $result->total()]);
    }
    
    #[Permission('删除')]
    public function delete()
    {
        if (request()->method() === 'DELETE') {
            $id = request()->get('id', 0);
            $filePath = public_path() . '/upload/' . File::where('id', $id)->value('file_path');
            $res = true;
            if (file_exists($filePath)) {
                $res = unlink($filePath);
            }
            if ($res) {
                File::destroy($id);
                return apiSuccess('删除成功');
            } else {
                return apiError('删除失败');
            }
        }
        return apiError('删除失败');
    }
    
    public function upload()
    {
        $result = UploadFile::upload();
        if (!empty($result['errMsg'])) {
            return apiError($result['errMsg']);
        }
        return apiSuccess('上传成功', $result);
    }
}